package com.orderVideo.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.orderVideo.common.Result;
import com.orderVideo.entity.User;
import com.orderVideo.service.UserService;
import com.orderVideo.util.JwtUtil;
import com.orderVideo.utils.LoginUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    
    private static final ObjectMapper objectMapper = new ObjectMapper();

    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            this.handleInvalidToken(response);
            return false;
        }

        // 验证token是否有效
        if (!JwtUtil.validateToken(token)) {
            this.handleInvalidToken(response);
            return false;
        }

        // 检查token是否过期
        if (JwtUtil.isTokenExpired(token)) {
            this.handleTokenExpired(response);
            return false;
        }

        // 设置当前登录用户ID
        Long userId = JwtUtil.getUserIdFromToken(token);
        User user = new User();
        user.setUserId(userId);
        LoginUser.setUser(user);
        
        return true;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 清除当前线程的用户信息
        LoginUser.remove();
    }
    
    /**
     * 处理token过期情况
     */
    private void handleTokenExpired(HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write(objectMapper.writeValueAsString(Result.error(401, "登录已过期，请重新登录")));
    }
    
    /**
     * 处理token无效情况
     */
    private void handleInvalidToken(HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write(objectMapper.writeValueAsString(Result.error(401, "无效的登录信息，请重新登录")));
    }
} 